package com.hairline.hairlinemarket.service.impl;

import com.hairline.hairlinemarket.bean.*;
import com.hairline.hairlinemarket.bean.vo.CartVo;
import com.hairline.hairlinemarket.mapper.*;
import com.hairline.hairlinemarket.service.CartService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Author:杨小凯
 * Date:2023-04-21 16:10
 * Description:<描述>
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private MarketCartMapper marketCartMapper;
    @Autowired
    private MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    private MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Override
    public BigDecimal selectCountByUserId(Integer userId) {
        BigDecimal count = marketCartMapper.selectGoodsCount(userId);
        return count;
    }

    @Override
    public boolean selectExist(Integer userId, Integer productId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);
        if (marketCarts != null && marketCarts.size() > 0) {
            return true;
        }
        return false;
    }

    // 更新购物车数量
    @Override
    public boolean updateNumber(Integer userId,Integer number, Integer productId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<MarketCart> cartList = marketCartMapper.selectByExample(example);
        MarketCart cart = cartList.get(0);
        Short originNumber = cart.getNumber();
        MarketCart marketCart = new MarketCart();
        marketCart.setNumber((short) (number+originNumber));
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(productId).andDeletedEqualTo(false);
        int update = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        if (update > 0) {
            return false;
        }
        return true;
    }

    @Override
    public MarketCart selectSpe(Integer userId, Integer productId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);
        if (marketCarts != null && marketCarts.size() > 0) {
            return marketCarts.get(0);
        }
        return null;
    }

    @Override
    public List<MarketCart> selectByUserId(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<MarketCart> cartList = marketCartMapper.selectByExample(cartExample);
        return cartList;
    }

    @Override
    public Map<String, BigDecimal> selectTotal(Integer userId) {
        HashMap<String, BigDecimal> map = new HashMap<>();

        BigDecimal checkedGoodsAmount = marketCartMapper.selectCheckedGoodsAmount(userId);
        if (checkedGoodsAmount==null){
            checkedGoodsAmount = BigDecimal.valueOf(0);
        }
        BigDecimal checkedGoodsCount = marketCartMapper.selectGoodsCount(userId);
        BigDecimal goodsAmount = marketCartMapper.selectGoodsCount(userId);
        BigDecimal goodsCount = marketCartMapper.selectGoodsCount(userId);
        map.put("checkedGoodsAmount", checkedGoodsAmount);
        map.put("checkedGoodsCount", checkedGoodsCount);
        map.put("goodsAmount", goodsAmount);
        map.put("goodsCount", goodsCount);
        return map;
    }

    /**
     * 向购物车中添加数据
     *
     * @param userId
     * @param goodsId
     * @param number
     * @param productId
     */
    @Override
    public void insertData(Integer userId, Integer goodsId, Integer number, Integer productId) {
        MarketCart record = new MarketCart();
        record.setNumber(number.shortValue());
        record.setGoodsId(goodsId);
        record.setProductId(productId);
        record.setUserId(userId);
        // TODO cart中的其他字段
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andIdEqualTo(productId).andGoodsIdEqualTo(goodsId);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);

        MarketGoodsProduct marketGoodsProduct = marketGoodsProducts.get(0);
        record.setPrice(marketGoodsProduct.getPrice());
        record.setSpecifications(Arrays.toString(marketGoodsProduct.getSpecifications()));
        record.setPicUrl(marketGoodsProduct.getUrl());
        record.setGoodsSn(String.valueOf(goodsId));
        // 查询goodsName
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andGoodsSnEqualTo(String.valueOf(goodsId));
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);

        record.setGoodsName(marketGoods.get(0).getName());
        marketCartMapper.insertSelective(record);
    }

    @Override
    public void deleteByUPId(Integer userId, Integer productId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        int delete = marketCartMapper.deleteByExample(cartExample);
    }

    @Override
    public Integer selectByUPId(Integer userId, Integer productId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<MarketCart> cartList = marketCartMapper.selectByExample(cartExample);
        MarketCart marketCart = cartList.get(0);
        return marketCart.getId();
    }

    @Override
    public Integer updateChecked(Integer userId, Integer isChecked, ArrayList productIds) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andProductIdIn(productIds).andDeletedEqualTo(false);

        MarketCart marketCart = new MarketCart();
        if (isChecked == 1) {
            marketCart.setChecked(true);
        } else {
            marketCart.setChecked(false);
        }
        int update = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        return update;
    }

    // 结算封装
    @Override
    public Map selectCartReslute(CartVo cartVo) {
        HashMap<String, Object> map = new HashMap<>();
        // 获取信息
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人id信息
            Integer userId = principal.getId();

            if (cartVo.getCartId()==0){
                // 购物车下单
                // 直接结算
                map = getCheckout(cartVo, userId);
            }else{
                // 商品详情页下单
                // 将cart中的其他商品的checked变为false
                MarketCart marketCart = new MarketCart();
                marketCart.setChecked(false);
                MarketCartExample example = new MarketCartExample();
                example.createCriteria().andProductIdEqualTo(cartVo.getCartId()).andDeletedEqualTo(false);
                marketCartMapper.updateByExampleSelective(marketCart, example);
                // 结算订单
                map = getCheckout(cartVo, userId);
            }
        }
        return map;
    }

    @Override
    public List<MarketCart> selectByUPs(Integer userId, List<Integer> productIds) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andProductIdIn(productIds);
        List<MarketCart> cartList = marketCartMapper.selectByExample(marketCartExample);
        return cartList;
    }

    @Override
    public void updateNumberById(Integer id, Integer number) {
        MarketCart record = new MarketCart();
        record.setNumber(number.shortValue());
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andIdEqualTo(id);
        marketCartMapper.updateByExampleSelective(record, example);
    }


    private HashMap<String, Object> getCheckout(CartVo cartVo, Integer userId) {
        // 查询当前用户选择的商品的总金额
        double goodsTotalPrice = marketCartMapper.selectCheckedGoodsAmount(userId).doubleValue();

        // 优惠券值
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(cartVo.getCouponId());
        double couponPrice;
        if (marketCoupon!=null){
            couponPrice = marketCoupon.getDiscount().doubleValue();
        }else {
            couponPrice = 0;
        }
        // TODO 运费需要判断地址
        double freightPrice=0;
        // TODO 组团
        double grouponPrice=0;
        // 实付订单货物金额：获取总金额 - 优惠券 - 组团
        double actualPrice=goodsTotalPrice - couponPrice - grouponPrice;

        // 订单总金额：实付订单货物金额+运费
        double orderTotalPrice=actualPrice + freightPrice;

        // 可用优惠券数量
        // 查询用户拥有的优惠券
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(couponUserExample);
        Integer availableCouponLength=marketCouponUsers.size();

        // 查询地址
        MarketAddress checkedAddress = marketAddressMapper.selectByPrimaryKey(userId);

        // 选择的商品列表
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<MarketCart> checkedGoodsList = marketCartMapper.selectByExample(marketCartExample);

        HashMap<String, Object> map = new HashMap<>();
        map.put("actualPrice", actualPrice);
        map.put("addressId", cartVo.getAddressId());
        map.put("availableCouponLength", availableCouponLength);
        map.put("cartId", cartVo.getCartId());
        map.put("checkedAddress", checkedAddress);
        map.put("checkedGoodsList", checkedGoodsList);
        map.put("couponId", cartVo.getCouponId());
        map.put("couponPrice", couponPrice);
        map.put("freightPrice", freightPrice);
        map.put("goodsTotalPrice", goodsTotalPrice);
        map.put("grouponPrice", grouponPrice);
        map.put("grouponRulesId", cartVo.getGrouponRulesId());
        map.put("orderTotalPrice", orderTotalPrice);
        map.put("userCouponId", cartVo.getUserCouponId());

        return map;
    }
}
